const parallelLimit = require('run-parallel-limit')
const util = require("util");
const path = require("path");

const upload_single = require("./upload-single");
const speedtest = require("./speedtest");
const upload_split = require("./upload-split");


/**
 * 
 * @param {String[]} full_paths 
 * @param {Number} max_uploads 
 */
function upload(full_paths, max_uploads) {
  let paths = Array.from(full_paths);
  return new Promise((resolve) => {
    let errors = [];
    let tasks = paths.map(full_path => {
      return cb => {
        upload_single.uploadSingleForXTime(3, full_path)
          .then((o) => {
            if (o.ok) {
              console.log(path.basename(full_path));
              console.log(o.url);
            } else {
              errors.push({
                full_path: full_path,
                error_messages: o.msg
              })
            }
            cb(null, full_path);
          });
      }
    });

    parallelLimit(tasks, max_uploads, function (err, results) {
      console.log("\n\n parallel tasks done..");
      if(errors.length){
        console.error(`Errors occured:${util.inspect(errors)}`);
      }
      resolve();
    })
  })
}


/**
 * 
 * @param {String} full_path 
 * @returns {Promise<{result:Boolean,file_url:String,message:String[]}>}
 */
function uploadSinglePath(full_path) {
  return new Promise(resolve => {
    upload_single.uploadSingleForXTime(3, full_path).then(o => {
      resolve({ result: o.ok, file_url: o.url, message: o.msg })
    });
  })
}

module.exports = {
  upload: upload,
  uploadSinglePath: uploadSinglePath,
  speedtest:speedtest,
  upload_single:upload_single,
  upload_split:upload_split
}